package org.example.controller;

import org.example.model.Message;
import org.example.service.RabbitMQMessageService;
import org.example.service.RedisSessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/test")
public class TestController {

    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private RabbitMQMessageService rabbitMQMessageService;

    @Autowired
    private RedisSessionService redisSessionService;

    @PostMapping("/send-message")
    public String sendMessage(@RequestBody Message message) {
        try {
            if (message.getTargetUserId() != null) {
                rabbitMQMessageService.sendMessageToUser(message.getTargetUserId(), message);
                logger.info("通过API发送消息给用户 {}: {}", message.getTargetUserId(), message.getContent());
                return "消息发送成功";
            } else {
                rabbitMQMessageService.broadcastMessage(message);
                logger.info("通过API广播消息: {}", message.getContent());
                return "广播消息发送成功";
            }
        } catch (Exception e) {
            logger.error("发送消息失败", e);
            return "消息发送失败: " + e.getMessage();
        }
    }

    @GetMapping("/user-status/{userId}")
    public String getUserStatus(@PathVariable String userId) {
        boolean isOnline = redisSessionService.isUserOnline(userId);
        String server = redisSessionService.getUserServer(userId);
        
        if (isOnline) {
            return "用户 " + userId + " 在线，服务器: " + server;
        } else {
            return "用户 " + userId + " 离线";
        }
    }

    @GetMapping("/health")
    public String healthCheck() {
        return "WebSocket集群服务运行正常";
    }
}